#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_004.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_004.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test4.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nettle/sha.h>

int main() {
    // 初始化SHA-256上下文结构体
    struct sha256_ctx ctx;
    // 待计算哈希值的消息
    const char *message = "The quick brown fox jumps over the lazy dog";
    // 预期的SHA-256哈希值，这是通过标准的SHA-256算法计算出的已知哈希值
    const char *expected_hash = "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592";

    // 用来存储计算完成后的SHA-256哈希值
    uint8_t computed_hash[SHA256_DIGEST_SIZE];
    char hash_string[SHA256_DIGEST_SIZE*2 + 1];
    
    // 初始化SHA-256上下文
    sha256_init(&ctx);
    // 将数据添加到SHA-256上下文中进行处理
    sha256_update(&ctx, strlen(message), (const uint8_t *)message);
    // 完成哈希计算，获取最终的哈希值
    sha256_digest(&ctx, SHA256_DIGEST_SIZE, computed_hash);
    
    // 将计算得到的哈希值（字节形式）转换为十六进制字符串表示
    for (int i = 0; i < SHA256_DIGEST_SIZE; i++) {
        sprintf(hash_string + i*2, "%02x", computed_hash[i]);
    }
    hash_string[SHA256_DIGEST_SIZE*2] = '\\0'; // 在字符串末尾添加空字符('\\0')以标示字符串的结束

    // 打印出计算得到的SHA-256哈希值
    printf("计算得到的SHA-256哈希值: %s\\n", hash_string);
    
    // 对比计算得到的哈希值与预期的哈希值
    if (strcmp(hash_string, expected_hash) == 0) {
        printf("计算得到的哈希值与预期的哈希值匹配。\\n");
    } else {
        printf("计算得到的哈希值与预期的哈希值不匹配。\\n");
    }

    return EXIT_SUCCESS;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test4 nettle_test4.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test4")
        self.assertIn('计算得到的哈希值与预期的哈希值匹配。', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test4 nettle_test4.c')
